package com.bop.dehong.main;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;

import com.base.dehong.util.LogUtils;
import com.base.dehong.util.PreferencesUtils;
import com.bop.dehong.R;
import com.bop.dehong.base.ActManager;
import com.bop.dehong.base.DeHongApp;
import com.bop.dehong.broadcast.ScreenOnReceiver;
import com.bop.dehong.cart.ShoppingCartActivity;
import com.bop.dehong.category.CategoryActivity;
import com.bop.dehong.center.PersonalCenterActivity;
import com.bop.dehong.config.Config;
import com.bop.dehong.home.HomeActivity;
import com.bop.dehong.login.LoginActivity;
import com.bop.dehong.main.BottomBarActivity.onBottomBarListener;
import com.bop.dehong.util.LockScreenUtil;
import com.bop.dehong.util.UpdateManager;
import com.umeng.analytics.MobclickAgent;



public class MainActivity extends BottomBarActivity implements onBottomBarListener {
	
	private List<Fragment> mFragments = new ArrayList<Fragment>();
	
	private HomeActivity mHomeActivity;
	private CategoryActivity mCategoryActivity;
	private ShoppingCartActivity mShoppingCartActivity;
	private PersonalCenterActivity mPersonalCenterActivity;
	private Dialog exitDialog; 
	private ScreenOnReceiver screenReceiver;
	private HomeWatcherReceiver mHomeKeyReceiver;
	private boolean go2background;
	private UpdateManager updateManager;

	private  void registerHomeKeyReceiver(Context context) {
	    LogUtils.e("homekey", "registerHomeKeyReceiver");
	    mHomeKeyReceiver = new HomeWatcherReceiver(context);
	    final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
	    context.registerReceiver(mHomeKeyReceiver, homeFilter);
	}

	private  void unregisterHomeKeyReceiver(Context context) {
	    LogUtils.e("homekey", "unregisterHomeKeyReceiver");
	    if (null != mHomeKeyReceiver) {
	        context.unregisterReceiver(mHomeKeyReceiver);
	        mHomeKeyReceiver = null;
	    }
	}
	    
	@Override
	protected List<Fragment> getFragments() {
		return mFragments;
	}
	
	@Override
	protected void initUI() {
		super.initUI();
		mViewPager.setScanScroll(false);
		setBottomBarListener(this);
        registerScreenReceiver();
        registerHomeKeyReceiver(this);
        if (updateManager == null)
		{
        	updateManager = new UpdateManager(this);
		}
		updateManager.update("");
	}
	
	
	private void registerScreenReceiver(){
		if (screenReceiver == null) {
			screenReceiver = new ScreenOnReceiver();
		}
		IntentFilter filter = new IntentFilter();    
		filter.addAction(Intent.ACTION_SCREEN_ON);    
		registerReceiver(screenReceiver , filter);
	}
	

	private void unregisterReceiver() {
		if (screenReceiver != null) {
			unregisterReceiver(screenReceiver);
			screenReceiver = null;
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (go2background) {
			LockScreenUtil.getInstance().go2Foreground(this);
			go2background = false;
		}
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (exitDialog != null) {
    		exitDialog.dismiss();
    		exitDialog = null;
		}	
		unregisterReceiver();
		unregisterHomeKeyReceiver(this);
	}
	
	@Override
	protected List<View> getBottomViews() {
		// TODO Auto-generated method stub
		List<View> bottoms = new ArrayList<View>();
		bottoms.add(getView(R.id.main_home_bar));
		bottoms.add(getView(R.id.main_category_bar));
		bottoms.add(getView(R.id.main_shopping_cart_bar));
		bottoms.add(getView(R.id.main_personal_center_bar));
		return bottoms;
	}

	@Override
	protected void initFragments() {
		mHomeActivity = new HomeActivity();
		mCategoryActivity = new CategoryActivity();
		mShoppingCartActivity = new ShoppingCartActivity();
		mPersonalCenterActivity = new PersonalCenterActivity();
		
		mFragments.add(mHomeActivity);
		mFragments.add(mCategoryActivity);
		mFragments.add(mShoppingCartActivity);
		mFragments.add(mPersonalCenterActivity);
		
		
	}
	/**
	 * 跳转
	 * @param page
	 */
	public void go2Page(int page){
		turnTargetView(page);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		int page = intent.getIntExtra("page", -1);
		if (page > -1) {
			turnTargetView(page,false);
		}
	
	}
	
	@Override
	protected int getContentViewId() {
		return R.layout.bottom_bar;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			getExitDialog();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 退出对话框
	 */
	private void getExitDialog() {
		exitDialog = new Dialog(this, R.style.MyDialogStyle);
		View view = View.inflate(this, R.layout.dialog_layout, null);
		exitDialog.setContentView(view);
		exitDialog.setCancelable(false);
		Button exitBtn = getView(view, R.id.btn_sure);
		Button cancelBtn = getView(view, R.id.btn_cancel);
		registerOnClickListener(exitBtn, cancelBtn);
		exitDialog.show();
	}

	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_sure:
			if (exitDialog != null) {
	    		exitDialog.dismiss();
	    		exitDialog = null;
			}
			
			if (DeHongApp.mLoginEntity != null) {
				DeHongApp.mLoginEntity = null;
			}
			if (DeHongApp.mUserInfo != null) {
				DeHongApp.mUserInfo = null;
			}
			unregisterReceiver();
			unregisterHomeKeyReceiver(this);
			PreferencesUtils.putLong(MainActivity.this, "gesturetime", System.currentTimeMillis() / 1000);
			MobclickAgent.onKillProcess(MainActivity.this);
			ActManager.getAppManager().AppExit();
			break;
		case R.id.btn_cancel:
			if (exitDialog != null) {
	    		exitDialog.dismiss();
	    		exitDialog = null;
			}
			break;

		default:
			break;
		}
	}
	
	private int position;
	
	@Override
	public boolean nBottomBar(int position) {
		if (position == 3 && DeHongApp.mLoginEntity == null) {
			Intent intent = new Intent(this, LoginActivity.class);
			intent.putExtra(Config.GO_BACK, true);
			this.position = position;
			startActivityForResult(intent, 100);
			return true;
		}
		return false;
	}
	
	@Override
	protected void onActivityResult(int arg0, int resultCode, Intent arg2) {
		super.onActivityResult(arg0, resultCode, arg2);
		if (resultCode != RESULT_OK) {
			return;
		}
		if (arg0 == 100) {
			turnTargetView(position, false);
		}
	}
	
	class HomeWatcherReceiver extends BroadcastReceiver{
		private static final String LOG_TAG = "HomeReceiver";
		private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
		private static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
		private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
		private static final String SYSTEM_DIALOG_REASON_LOCK = "lock";
		private static final String SYSTEM_DIALOG_REASON_ASSIST = "assist";
		Context context;
		
		public HomeWatcherReceiver(Context context) {
			this.context = context;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			 String action = intent.getAction();
		        LogUtils.e(LOG_TAG, "onReceive: action: " + action);
		        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
		            // android.intent.action.CLOSE_SYSTEM_DIALOGS
		            String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
		            LogUtils.e(LOG_TAG, "reason: " + reason);

		            if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
		                // 短按Home键
		            	 LogUtils.e(LOG_TAG, "homekey");
		            	if (LockScreenUtil.getInstance().isAppOnForeground(context)) {
		            		go2background = moveTaskToBack(true);
		            		LogUtils.e(LOG_TAG, "go2bg=" + go2background);
		            		LockScreenUtil.getInstance().go2Backstage(context);
						}
		            }
		            else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {
		                // 长按Home键 或者 activity切换键
		            	 LogUtils.e(LOG_TAG, "long press home key or activity switch");

		            }
		            else if (SYSTEM_DIALOG_REASON_LOCK.equals(reason)) {
		                // 锁屏
		            	 LogUtils.e(LOG_TAG, "lock");
		            }
		            else if (SYSTEM_DIALOG_REASON_ASSIST.equals(reason)) {
		                // samsung 长按Home键
		            	 LogUtils.e(LOG_TAG, "assist");
		            }

		        }
		}

	}
}
